<?php
/*
 * @author:qiushaochang
 * @date:2023/8/11
*/

namespace crmeb\services\pay\storage;

use app\model\order\Orders;
use crmeb\exceptions\ApiException;
use crmeb\services\pay\BasePay;
use crmeb\services\pay\PayInterface;
use think\facade\Config;
use crmeb\services\pay\extend\quicknpay\QuicknPay as QuicknPayService;
use think\facade\Log;
use think\helper\Arr;
use app\services\order\OrderService;

/**
 *
 */
class QuicknPay extends BasePay implements PayInterface
{
    /**
     * @var QuicknPayService
     */
    private $pay;

    /**
     * @param array $config
     * @return mixed|void
     * @author:qiushaochang
     * @date:2023/8/14
     */
    protected function initialize(array $config)
    {
        $config    = Config::get('pay.stores.quickn_pay');
        $this->pay = new QuicknPayService($config);
    }

    public function create(string $sn, string $totalFee, string $attach, string $body, string $detail, array $options = [])
    {
        $data = [
            'invoice' => $sn,
            'amount' => $totalFee,
            'payment_desc' => 'Sample payment description',
            'currency' => 'MYR',
            'buyer_name' => 'John',
            'buyer_email' => 'john@email.com',
            'phone' => '601731233321',
            'add_line_1' => 'Address line 1',
            'add_line_2' => 'Address line 2',
            'postcode' => '41000',
            'city' => 'Petaling Jaya',
            'comment' => 'Sample comment from payer',
            'bank_code' => $options['bank_code'],
            'respond' => '1',
            'skip_receipt' => '0',
            'card_number' => '1111222233334444',
            'card_year' => '12',
            'card_month' => '22',
            'card_cvv' => '123',
//            'callback_url_be' => 'https://da8a-58-48-71-10.ngrok-free.app?order_no=56757dkkd9dd',
//            'callback_url_fe_succ' => 'https://da8a-58-48-71-10.ngrok-free.app?order_no=56757dkkd9dd',
//            'callback_url_fe_fail' => 'https://tg.51.com/authcallback/cbbing'
        ];
        return $this->pay->directPay($data);
    }

    public function merchantPay(string $openid, string $orderId, string $amount, array $options = [])
    {
        // TODO: Implement merchantPay() method.
    }

    public function refund(string $outTradeNo, array $options = [])
    {
        // TODO: Implement refund() method.
    }

    public function queryRefund(string $outTradeNo, string $outRequestNo, array $other = [])
    {
        // TODO: Implement queryRefund() method.
    }

    /**
     * [fpx_fpxTxnId] => 1808241535340347
    [fpx_sellerId] => sE000008567
    [invoice_no] => INV10154632
    [txn_status] => 00
    [msg] => Transaction Approved
    [txn_amount] => 192.00
    [pay_method] => fpx
    [hash] => fc85b97551f5a2bgbf28d916f2f8055d
    [type] => quickn_pay
     * @return mixed|string
     */
    public function handleNotify()
    {
        $params = request()->all();
        $requestHash = Arr::get($params,'hash');
        unset($params['hash'], $params['type']);
        $hash = $this->pay->sign($params);
        if ($hash != $requestHash) {
            //throw new ApiException('非法请求');
        }
        if(isset($params['txn_status']) && $params['txn_status'] != '00'){//交易失败,先记录日志
            Log::error(json_encode($params));
        }

        //获取交易订单号
        switch($params['pay_method']){
            case 'fpx':
                $trx_id = $params['fpx_fpxTxnId'];
                break;
            case 'paypal':
                $trx_id = $params['paypal_trx_id'];
                break;
            case 'mastercard':
                $trx_id = $params['mastercard_trx_id'];
                break;
            case 'others':
                $trx_id = $params['others_trx_id'];
                break;
            default:
                $trx_id = '';
        }

        $sn = $params['invoice_no'];
        $order = Orders::where('sn', $sn)->find()->toArray();
        if($order['price'] != $params['txn_amount']){
            throw new ApiException('非法请求');
        }

        $servers = new OrderService();
        $servers->paySuccess([
            'order_id' => $order['id'],
            'pay_sn' => $trx_id,
            'user_id' => $order['uid']
        ]);
        return "OK";
        //TODO 。。。
    }
}